// pages/book-detail/bookDetail.js
import { BookModel } from '../../models/book.js'
import { LikeModel } from '../../models/like.js'

const likeModel = new LikeModel()
const bookModel = new BookModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    book: null,
    likeStatus: false,
    likeCount: 0,
    posting:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //显示数据加载中图
    wx.showLoading()
    //获取传递的数据id
    const id = options.bid
    const detail = bookModel.getBookDetail(id)
    const comments = bookModel.getShortComments(id)
    const likes = bookModel.getLikeStatus(id)

    Promise.all([detail,comments,likes])
    .then(res=>{
     this.setData({
       book:res[0],
       comments: res[1].comments,
       likeStatus: res[2].like_status,
       likeCount: res[2].fav_nums
     })
     //关闭数据加载图
      wx.hideLoading()
    })
  },
  //点赞
  onLike: function (event) {
    let behavior = event.detail.behavior
    likeModel.updateLike(behavior, this.data.book.id, 400)
  },
  //点击输入短评
  onFakePost:function(){
    this.setData({
      posting:true
    })
  },
  onCancel:function(){
    this.setData({
      posting: false
    })
  },
  //添加短评
  onPost:function(event){
    //短评值可能是输入的，或者直接点击已有标签获得的
    const comment = event.detail.value || event.detail.text
   if(!comment){
     return
   }
   if(comment.length>12){
     wx.showToast({
       title: '短评最多12个字',
       icon: 'none'
     })
     return
   }
   //调添加短评接口
    bookModel.addBookComment(this.data.book.id, comment)
    .then(res=>{
      wx.showToast({
        title: '+1',
        icon: 'none'
      })
      //将新短评添加到页面短评数组中,关闭短评输入面板
      this.setData({
        comments: [{ content: comment,nums: 1},...this.data.comments],
        posting: false,
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})